// 建立连接
//const serviceUrl = "http://10.12.115.70:20001/api/WCSMS/monitor";
const serviceUrl = "http://wishhightech.kmdns.net:3000/message";
// const serviceUrl = "http://localhost:20001/api/WCSMS/monitor";
let connection = "";
const signalRConnect = () => {
  connection = new signalR.HubConnectionBuilder()
  .withUrl(serviceUrl, {
    skipNegotiation: true,  // 跳过协商
    transport: signalR.HttpTransportType.WebSockets // 强制使用 WebSocket
  })
  .withAutomaticReconnect()
  .build();
  connection.keepAliveIntervalInMilliseconds = 5000;
  connection.onreconnected(async (id) => {
    console.info("已自动重新连接:" + message);
  });
  connection.onclose(async (error) => {
    if (error) {
      // 异常断开时,需要手动重新连接
      await connection.start();
    } else {
      console.info("已断开连接");
    }
  });
};
// signalR初始化,接收函数
const signalRMonitorInit = (onStationData, onLocationData) => {
  connection
    .start()
    .then(() => {
      const message = "Layout|01";
      connection.invoke("Connected", message);
    })
    .catch((err) => {
      console.log(err);
    });

  // 在这里添加回调触发
  connection.on("LocationLayoutData", (msg) => {
    let response = JSON.parse(msg);
    //console.log("res:----------------------------------------", response);
    if (onLocationData) onLocationData(response); // 触发新回调
  });
  connection.on("PortLayoutData", (msg) => {
    let response = JSON.parse(msg);
    // 遍历并添加 devType 属性
    if(Array.isArray(response)) {
        response.forEach(item => {
            item.devType = "COV"; // 给每个元素添加 COV 类型
            //if(item.containerCode==null)item.isFull ="0";
            if(item.description==="一楼人工入库点01")item.portName="rIn01";
            if(item.description==="一楼人工入库点02")item.portName="rIn02"
        });
    } else if(response && typeof response === 'object') {
        response.devType = "COV"; // 处理单个对象的情况
    }
    //console.log("res:----------------------------------------", response);
    coverDataToNew(response);
});

  connection.on("StationLayoutData", (msg) => {
    let response = JSON.parse(msg);
    if (onStationData) onStationData(response); // 触发回调
  });
};

function startUpdate(onStationData, onLocationData) {
  signalRConnect();
  signalRMonitorInit(onStationData, onLocationData);
}
